<template>
  <el-form ref="ruleFormRef" style="width: 600px;margin: auto;" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
  
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script setup lang="ts">
  import { reactive, ref, onMounted, computed } from 'vue'
  import axios from 'axios';
  import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useRoute, useRouter } from 'vue-router'
  const route = useRoute();
  const router = useRouter();
  
  const formSize = ref<ComponentSize>('default')
  const ruleFormRef = ref<FormInstance>()

  const form: any = reactive({
    roleName: '',
  })
  
  //规则
  const rules = reactive<FormRules>({
    roleName: [
      { required: true, message: '请输入角色名称', trigger: 'blur' },
    ],
  })
  
    //保存
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        let roleData: any = {
          roleName: form.roleName,
        }
        axios.post('/api/RoleManagement/Create', roleData).then(res => {
          console.log(res);
          if (res.data.code == 0) {
            ElMessage.success("保存成功!")
            router.push({
              'name':'RoleList'
            })
          } else if (res.data.code == -2) {
            ElMessage.error("该角色名已存在.请重新输入")
            return
          } else {
            ElMessage.error("保存失败!")
            return
          }
        }).catch(err => {
          console.log(err);
  
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
  </script>
  
  <style scoped>
  
  </style>